<template>
  <div class="logistics-monitor-container">
    <div class="search-section animate__animated animate__fadeInDown">
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入运输ID" v-model="transportId" prefix-icon="el-icon-document"></el-input>
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入订单ID" v-model="orderId" prefix-icon="el-icon-s-order"></el-input>
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入车辆ID" v-model="vehicleId" prefix-icon="el-icon-truck"></el-input>
      <el-button type="primary" @click="search" class="el-icon-search">搜索</el-button>
      <el-button type="warning" @click="reset" class="el-icon-refresh">重置</el-button>
      <el-button type="success" @click="showAddDialog" class="el-icon-plus">添加运输任务</el-button>
      <el-button :type="pollingEnabled ? 'info' : 'danger'" @click="togglePolling" :icon="pollingEnabled ? 'el-icon-open' : 'el-icon-turn-off'">
        {{ pollingEnabled ? '关闭事件轮询' : '开启事件轮询' }}
      </el-button>
    </div>

    <div class="table-section animate__animated animate__fadeInUp">
      <el-table
          :data="tableData" border stripe
          :header-cell-style="getRowClass"
          @selection-change="handleSelectionChange"
          row-key="transportId">
        
        <el-table-column prop="transportId" label="运输ID"></el-table-column>
        <el-table-column prop="orderId" label="订单ID"></el-table-column>
        <el-table-column prop="vehicleId" label="车辆ID"></el-table-column>
        <el-table-column prop="startLocation" label="起始地"></el-table-column>
        <el-table-column prop="endLocation" label="目的地"></el-table-column>
        <el-table-column prop="currentTemp" label="当前温度">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center;">
              <span :style="{ color: getTemperatureColor(scope.row.currentTemp) }">
                {{ scope.row.currentTemp }}°C
              </span>
              <el-button 
                size="mini" 
                type="info" 
                icon="el-icon-warning" 
                circle 
                style="margin-left: 10px;" 
                @click="checkTemperature(scope.row)"
                :title="'检查温度是否在产品安全范围内'"
              ></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="alertStatus" label="告警状态">
          <template slot-scope="scope">
            <el-tag :type="getAlertType(scope.row.alertStatus)">
              {{ getAlertText(scope.row.alertStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="运输状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button size="mini" type="success" @click="handleUpdateStatus(scope.row)">更新状态</el-button>
              <el-button size="mini" type="info" @click="handleViewHistory(scope.row)">查看历史</el-button>
            </div>
          </template>
        </el-table-column>
        
        <template slot="empty">
          <div style="padding: 30px;">
            <el-empty description="暂无运输记录数据">
              <el-button type="primary" @click="showAddDialog">创建第一条运输记录</el-button>
            </el-empty>
          </div>
        </template>
      </el-table>

      <div class="block" style="padding:10px 0;align-content: center;margin-left: 30%;margin-top:30px;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加运输任务对话框 -->
    <el-dialog title="添加运输任务" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId"></el-input>
        </el-form-item>
        <el-form-item label="车辆ID" prop="vehicleId">
          <el-input v-model="form.vehicleId"></el-input>
        </el-form-item>
        <el-form-item label="起始地" prop="startLocation">
          <el-input v-model="form.startLocation"></el-input>
        </el-form-item>
        <el-form-item label="目的地" prop="endLocation">
          <el-input v-model="form.endLocation"></el-input>
        </el-form-item>
        <el-form-item label="初始温度" prop="currentTemp">
          <el-input-number v-model="form.currentTemp" :min="-50" :max="50"></el-input-number>
        </el-form-item>
        <el-form-item label="产品ID" prop="productId">
          <el-input-number v-model="form.productId" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="最低温度" prop="minTemp">
          <el-input-number v-model="form.minTemp" :min="-50" :max="50"></el-input-number>
        </el-form-item>
        <el-form-item label="最高温度" prop="maxTemp">
          <el-input-number v-model="form.maxTemp" :min="-50" :max="50"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog title="更新状态" :visible.sync="statusDialogVisible" width="30%">
      <el-form :model="statusForm" :rules="statusRules" ref="statusForm" label-width="100px">
        <el-form-item label="运输ID">
          <el-input v-model="statusForm.transportId" disabled></el-input>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="运输中" value="1"></el-option>
            <el-option label="已完成" value="2"></el-option>
            <el-option label="已取消" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateStatusSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 温度历史记录对话框 -->
    <el-dialog title="温度历史记录" :visible.sync="historyDialogVisible" width="50%">
      <el-table :data="temperatureHistory" border stripe>
        <el-table-column prop="timestamp" label="时间"></el-table-column>
        <el-table-column prop="temperature" label="温度">
          <template slot-scope="scope">
            <span :style="{ color: getTemperatureColor(scope.row.temperature) }">
              {{ scope.row.temperature }}°C
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="alertType" label="告警类型">
          <template slot-scope="scope">
            <el-tag :type="getAlertType(scope.row.alertType)">
              {{ getAlertText(scope.row.alertType) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';
import { 
  createTransport, 
  updateTemperature, 
  updateTransportStatus, 
  getTransport, 
  getTemperatureHistoryCount,
  getTemperatureHistory,
  subscribeTemperatureAlertEvent,
  getTransportIdByOrder,
  getAllTransports,
  subscribeTransportCreatedEvent,
  handleContractError
} from '@/utils/LogisticsMonitor';
import { handleTemperatureAlertEvent } from '@/utils/errorHandler';

export default {
  name: "LogisticsMonitor",
  data() {
    return {
      pageSize: 10,
      pageNum: 1,
      transportId: '',
      orderId: '',
      vehicleId: '',
      tableData: [],
      total: 0,
      addDialogVisible: false,
      statusDialogVisible: false,
      historyDialogVisible: false,
      temperatureHistory: [],
      form: {
        orderId: '',
        vehicleId: '',
        startLocation: '',
        endLocation: '',
        currentTemp: 0,
        productId: 1,
        minTemp: 2,
        maxTemp: 8
      },
      statusForm: {
        transportId: '',
        status: ''
      },
      rules: {
        orderId: [
          { required: true, message: '请输入订单ID', trigger: 'blur' }
        ],
        vehicleId: [
          { required: true, message: '请输入车辆ID', trigger: 'blur' }
        ],
        startLocation: [
          { required: true, message: '请输入起始地', trigger: 'blur' }
        ],
        endLocation: [
          { required: true, message: '请输入目的地', trigger: 'blur' }
        ],
        currentTemp: [
          { required: true, message: '请输入温度', trigger: 'blur' }
        ],
        productId: [
          { required: true, message: '请输入产品ID', trigger: 'blur' }
        ]
      },
      statusRules: {
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      wsConnections: [], // 存储轮询控制器
      pollingEnabled: true,
    }
  },
  created() {
    this.load();
    // 订阅温度告警事件
    this.subscribeToAlerts();
  },
  methods: {
    async load(forceRefresh = false) {
      try {
        console.log('开始加载数据, forceRefresh:', forceRefresh);
        
        // 如果有运输ID，则获取特定运输信息
        if (this.transportId) {
          console.log('按运输ID查询:', this.transportId);
          const transportId = parseInt(this.transportId);
          if (isNaN(transportId)) {
            this.$message.warning('无效的运输ID，请输入数字');
            this.tableData = [];
            this.total = 0;
            return;
          }
          try {
            const transport = await getTransport(transportId);
            console.log('获取到运输数据:', transport);
            
            if (!transport || !transport.transportId) {
              this.$message.warning(`找不到ID为 ${transportId} 的运输记录`);
              this.tableData = [];
              this.total = 0;
              return;
            }
            
            this.tableData = [transport];
            console.log('设置表格数据为单条记录');
          } catch (err) {
            console.error('获取运输信息失败:', err);
            this.$message.error('获取运输信息失败: ' + (err.message || '未知错误'));
            this.tableData = [];
            this.total = 0;
            return;
          }
        } 
        // 如果有订单ID，则通过订单ID获取运输信息
        else if (this.orderId) {
          console.log('按订单ID查询:', this.orderId);
          try {
            const transportId = await getTransportIdByOrder(this.orderId);
            console.log('订单对应的运输ID:', transportId);
            
            if (!transportId) {
              this.$message.warning(`找不到订单 ${this.orderId} 对应的运输记录`);
              this.tableData = [];
              this.total = 0;
              return;
            }
            
            const transport = await getTransport(transportId);
            if (!transport || !transport.transportId) {
              this.$message.warning(`找不到运输ID为 ${transportId} 的运输记录`);
              this.tableData = [];
              this.total = 0;
              return;
            }
            
            this.tableData = [transport];
            console.log('设置表格数据为单条记录');
          } catch (err) {
            console.error('获取订单对应运输信息失败:', err);
            this.$message.error('获取订单对应运输信息失败: ' + (err.message || '未知错误'));
            this.tableData = [];
            this.total = 0;
            return;
          }
        }
        // 否则获取所有运输信息
        else {
          console.log('查询所有运输记录');
          try {
            const transports = await getAllTransports(forceRefresh);
            console.log('获取到运输记录数组:', transports);
            
            if (!Array.isArray(transports) || transports.length === 0) {
              console.log('没有找到运输记录，显示空表格');
              this.tableData = [];
              this.$message.info('没有找到运输记录，请创建运输任务');
            } else {
              this.tableData = transports;
              console.log('设置表格数据，记录数:', transports.length);
            }
          } catch (err) {
            console.error('获取所有运输信息失败:', err);
            this.$message.error('获取所有运输信息失败: ' + (err.message || '未知错误'));
            this.tableData = [];
          }
        }
        
        this.total = this.tableData.length;
        console.log('总记录数:', this.total);
      } catch (error) {
        console.error('加载数据失败:', error);
        this.$message.error('加载数据失败: ' + (error.message || '未知错误'));
        this.tableData = [];
        this.total = 0;
      }
    },
    getRowClass({rowIndex, columnIndex}) {
      if(rowIndex === 0) {
        return 'background:#ccc'
      }
    },
    reset() {
      this.transportId = '';
      this.orderId = '';
      this.vehicleId = '';
      this.load();
    },
    search() {
      this.load(true);
    },
    showAddDialog() {
      // 生成一个更唯一的transportId
      const timestamp = Date.now();
      const randomSuffix = Math.floor(1000 + Math.random() * 9000);
      const uniqueId = parseInt(`${timestamp % 100000}${randomSuffix % 1000}`); // 组合时间戳和随机数
      
      // 预填一些示例数据方便用户创建
      this.form = {
        orderId: 'ORDER-' + Math.floor(1000 + Math.random() * 9000),  // 随机4位数订单号
        vehicleId: '京A' + Math.floor(10000 + Math.random() * 90000),  // 随机5位数车牌
        startLocation: '北京',
        endLocation: '上海',
        currentTemp: Math.floor(2 + Math.random() * 6),  // 2-8度随机温度
        productId: 101,  // 默认产品ID
        minTemp: 2,      // 默认最低温度
        maxTemp: 8       // 默认最高温度
      };
      this.addDialogVisible = true;
      
      // 记录在控制台，便于调试
      console.log('预生成唯一运输ID:', uniqueId);
    },
    handleAdd() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 生成一个更唯一的transportId
          const timestamp = Date.now();
          const randomSuffix = Math.floor(1000 + Math.random() * 9000);
          const newTransportId = parseInt(`${timestamp % 100000}${randomSuffix % 1000}`); // 组合时间戳和随机数
          
          // 传递合约需要的参数，包括温度范围
          const formData = {
            transportId: newTransportId,
            orderId: this.form.orderId,
            currentTemp: this.form.currentTemp,
            productId: this.form.productId,
            minTemp: this.form.minTemp,
            maxTemp: this.form.maxTemp
          };

          // 进行温度范围验证
          if (formData.minTemp >= formData.maxTemp) {
            this.$message.error('温度范围错误：最低温度必须小于最高温度');
            return;
          }

          console.log('创建运输任务参数:', formData);

          // 保存所有表单数据到本地存储
          const localData = {
            transportId: newTransportId,
            orderId: this.form.orderId,        // 保存订单ID到本地
            vehicleId: this.form.vehicleId,
            startLocation: this.form.startLocation,
            endLocation: this.form.endLocation,
            currentTemp: this.form.currentTemp,
            productId: this.form.productId,
            minTemp: this.form.minTemp,
            maxTemp: this.form.maxTemp
          };
          
          // 先保存本地数据，确保前端有记录
          this.saveLocalTransportData(localData);
          
          // 隐藏对话框并显示加载中提示
          this.addDialogVisible = false;
          this.$message({
            message: '正在创建运输任务...',
            type: 'info',
            duration: 2000
          });
          
          // 尝试创建运输任务
          createTransport(formData).then(res => {
            console.log('创建运输任务响应:', res);
            
            if (res.code === '200') {
              this.$message.success('添加成功');
              // 强制刷新以显示新数据
              this.load(true);
            } else {
              // 显示更具体的错误信息，但不阻止本地数据使用
              const errorMsg = res.msg || '添加失败，请检查输入参数';
              this.$message({
                message: errorMsg + '（已保存本地数据）',
                type: 'warning',
                duration: 5000
              });
              console.error('创建运输任务返回错误:', res);
              
              // 仍然刷新页面以显示本地保存的数据
              this.load(true);
            }
          }).catch(error => {
            console.error('创建运输任务失败:', error);
            
            // 尝试序列化错误对象以便于调试
            let errorDetail = '';
            try {
              if (typeof error === 'object') {
                errorDetail = JSON.stringify(error);
              } else {
                errorDetail = String(error);
              }
            } catch (e) {
              errorDetail = '无法序列化的错误对象';
            }
            
            console.log('详细错误信息:', errorDetail);
            
            // 显示错误提示，但提醒用户数据已本地保存
            this.$message({
              message: '合约调用失败（已保存本地数据）',
              type: 'warning',
              duration: 5000
            });
            
            // 仍然刷新页面以显示本地保存的数据
            this.load(true);
          });
        }
      });
    },
    
    // 保存额外的前端数据到本地存储
    saveLocalTransportData(data) {
      if (!data || !data.transportId) {
        console.error('保存本地数据失败: 无效的数据或缺少transportId');
        return;
      }
      
      try {
        console.log('保存数据到本地存储:', data);
        
        // 确保数据中包含订单ID
        if (!data.orderId && this.form && this.form.orderId) {
          data.orderId = this.form.orderId;
        }
        
        // 检查localStorage是否可用
        if (typeof localStorage === 'undefined') {
          console.error('localStorage不可用，无法保存数据');
          return;
        }
        
        const key = `transport_${data.transportId}`;
        
        // 读取现有数据
        let existingData = {};
        try {
          const storageData = localStorage.getItem('transportMetadata');
          if (storageData) {
            existingData = JSON.parse(storageData);
            if (!existingData || typeof existingData !== 'object') {
              console.warn('本地存储中的数据格式不正确，将重置');
              existingData = {};
            }
          }
        } catch (e) {
          console.error('解析本地存储数据失败，将重置:', e);
          existingData = {};
        }
        
        // 更新数据
        existingData[key] = {
          ...data,
          // 确保所有字段有有效值
          transportId: parseInt(data.transportId),
          orderId: data.orderId || `ORDER-${1000 + Math.floor(Math.random() * 9000)}`,
          vehicleId: data.vehicleId || `京A${10000 + Math.floor(Math.random() * 90000)}`,
          startLocation: data.startLocation || '北京',
          endLocation: data.endLocation || '上海',
          currentTemp: parseFloat(data.currentTemp || 5),
          productId: parseInt(data.productId || 101),
          minTemp: parseFloat(data.minTemp || 2),
          maxTemp: parseFloat(data.maxTemp || 8),
          createTime: data.createTime || new Date().toLocaleString()
        };
        
        console.log('更新后的存储数据:', existingData);
        
        // 保存回localStorage
        try {
          localStorage.setItem('transportMetadata', JSON.stringify(existingData));
          console.log('数据已成功保存到本地存储');
        } catch (e) {
          console.error('保存数据到localStorage失败:', e);
          
          // 尝试清理部分数据后再次保存
          try {
            // 如果数据太大，只保留当前项目
            const reducedData = { [key]: existingData[key] };
            localStorage.setItem('transportMetadata', JSON.stringify(reducedData));
            console.log('已保存精简数据到本地存储');
          } catch (e2) {
            console.error('保存精简数据也失败:', e2);
          }
        }
      } catch (error) {
        console.error('保存本地数据整体失败:', error);
      }
    },
    handleUpdateStatus(row) {
      this.statusForm = {
        transportId: row.transportId,
        status: row.status
      };
      this.statusDialogVisible = true;
    },
    handleUpdateStatusSubmit() {
      this.$refs.statusForm.validate((valid) => {
        if (valid) {
          const transportId = parseInt(this.statusForm.transportId);
          
          // 先隐藏对话框，显示进行中提示
          this.statusDialogVisible = false;
          this.$message({
            message: '正在更新状态...',
            type: 'info',
            duration: 2000
          });
          
          updateTransportStatus(transportId, this.statusForm.status)
            .then(res => {
              console.log('状态更新响应:', res);
              
              if (res.code === '200') {
                this.$message.success('状态更新成功');
                
                // 更新本地数据
                const localData = this.getLocalTransportData(transportId);
                if (localData) {
                  localData.status = this.statusForm.status;
                  this.saveLocalTransportData(localData);
                }
                
                // 刷新页面数据
                this.load(true);
              } else {
                const errorMsg = res.msg || '状态更新失败';
                this.$message({
                  message: errorMsg,
                  type: 'warning',
                  duration: 5000
                });
                console.error('状态更新返回错误:', res);
              }
            })
            .catch(error => {
              console.error('状态更新失败:', error);
              
              // 尝试获取格式化的错误对象
              const errorResponse = handleContractError(error);
              
              // 如果是交易成功但格式不符合预期
              if (errorResponse.code === '200') {
                this.$message.success('状态更新已提交');
                
                // 更新本地数据
                const localData = this.getLocalTransportData(transportId);
                if (localData) {
                  localData.status = this.statusForm.status;
                  this.saveLocalTransportData(localData);
                }
                
                // 刷新页面数据
                this.load(true);
              } else {
                this.$message.error(errorResponse.msg || '状态更新失败，请稍后再试');
              }
            });
        }
      });
    },
    async handleViewHistory(row) {
      try {
        const count = await getTemperatureHistoryCount(row.transportId);
        const history = [];
        for (let i = 0; i < count; i++) {
          const record = await getTemperatureHistory(row.transportId, i);
          history.push(record);
        }
        this.temperatureHistory = history;
        this.historyDialogVisible = true;
      } catch (error) {
        this.$message.error('获取温度历史记录失败');
      }
    },
    checkTemperature(row) {
      // 实现温度检查逻辑
      try {
        const currentTemp = parseFloat(row.currentTemp);
        const minTemp = parseFloat(row.minTemp || 2); // 默认最低温度2度
        const maxTemp = parseFloat(row.maxTemp || 8); // 默认最高温度8度
        
        let status = '';
        let message = '';
        let type = '';
        
        if (isNaN(currentTemp) || isNaN(minTemp) || isNaN(maxTemp)) {
          status = '无效数据';
          message = '温度数据无效，请检查数据格式';
          type = 'warning';
        } else if (currentTemp < minTemp) {
          status = '温度过低';
          message = `当前温度(${currentTemp}°C)低于安全最低温度(${minTemp}°C)，可能导致产品冻损`;
          type = 'danger';
        } else if (currentTemp > maxTemp) {
          status = '温度过高';
          message = `当前温度(${currentTemp}°C)高于安全最高温度(${maxTemp}°C)，可能导致产品变质`;
          type = 'danger';
        } else {
          status = '温度正常';
          message = `当前温度(${currentTemp}°C)在安全范围内(${minTemp}°C ~ ${maxTemp}°C)`;
          type = 'success';
        }
        
        // 显示更详细的温度检查结果
        this.$notify({
          title: `运输ID ${row.transportId} 温度检查结果: ${status}`,
          message: message,
          type: type,
          duration: 5000,
          position: 'bottom-right'
        });
        
        // 为便于调试，也在控制台输出
        console.log(`温度检查[${row.transportId}]:`, { currentTemp, minTemp, maxTemp, status, message });
      } catch (error) {
        console.error('温度检查出错:', error);
        this.$message.error('温度检查出现错误，请查看控制台');
      }
    },
    getTemperatureColor(temp) {
      if (temp > 30) return '#F56C6C';
      if (temp < 0) return '#409EFF';
      return '#67C23A';
    },
    getAlertType(status) {
      switch (status) {
        case 0: return 'success';
        case 1: return 'warning';
        case 2: return 'danger';
        default: return 'info';
      }
    },
    getAlertText(status) {
      switch (status) {
        case 0: return '正常';
        case 1: return '警告';
        case 2: return '危险';
        default: return '未知';
      }
    },
    getStatusType(status) {
      switch (status) {
        case '1': return 'primary';
        case '2': return 'success';
        case '3': return 'info';
        default: return 'info';
      }
    },
    getStatusText(status) {
      switch (status) {
        case '1': return '运输中';
        case '2': return '已完成';
        case '3': return '已取消';
        default: return '未知';
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.load();
    },
    async subscribeToAlerts() {
      try {
        // 订阅温度告警事件，调整轮询时间为30秒以减少请求次数
        const tempController = await subscribeTemperatureAlertEvent((event) => {
          console.log('收到温度告警:', event);
          const { transportId, alertType } = event;
          
          // 仅在数据变化时才刷新数据，且只刷新变化的行
          this.tableData = this.tableData.map(row => {
            if (row.transportId === transportId) {
              return { ...row, alertStatus: alertType };
            }
            return row;
          });
          
          // 不再主动调用 this.load() 来减少不必要的请求
        }, 30000); // 增加轮询间隔到30秒
        
        // 订阅运输创建事件，调整轮询时间为30秒以减少请求次数
        const transportController = await subscribeTransportCreatedEvent((event) => {
          console.log('收到运输创建事件:', event);
          const { transportId, productId } = event;
          
          // 只有在此事件触发时才获取最新数据，且只获取新增的记录
          getTransport(transportId).then(transport => {
            if (transport && transport.transportId) {
              // 直接将新记录添加到表格中，避免重新加载全部数据
              this.tableData.push(transport);
              this.total = this.tableData.length;
            }
          }).catch(() => {
            // 静默处理错误
          });
          
          // 不再主动调用 this.load() 来减少不必要的请求
        }, 30000); // 增加轮询间隔到30秒
        
        // 保存轮询控制器
        this.wsConnections.push(tempController, transportController);
      } catch (error) {
        console.error('订阅事件失败:', error);
        setTimeout(() => {
          this.subscribeToAlerts();
        }, 10000); // 增加重试间隔到10秒
      }
    },
    togglePolling() {
      this.pollingEnabled = !this.pollingEnabled;
      if (this.pollingEnabled) {
        this.$message.info('已启用事件轮询');
        this.subscribeToAlerts();
      } else {
        this.$message.info('已关闭事件轮询');
        this.wsConnections.forEach(controller => {
          if (controller && typeof controller.stop === 'function') {
            controller.stop();
          }
        });
        this.wsConnections = []; // 清空控制器列表
      }
    },
    beforeDestroy() {
      // 组件销毁前停止所有轮询
      this.wsConnections.forEach(controller => {
        if (controller && typeof controller.stop === 'function') {
          controller.stop();
        }
      });
    },
    // 添加一个用于从utils获取本地数据的函数
    getLocalTransportData(transportId) {
      try {
        if (typeof localStorage === 'undefined') {
          console.warn('localStorage不可用');
          return null;
        }
        
        const key = `transport_${transportId}`;
        const storageData = localStorage.getItem('transportMetadata');
        
        if (!storageData) {
          return null;
        }
        
        const allData = JSON.parse(storageData);
        if (!allData || typeof allData !== 'object') {
          return null;
        }
        
        return allData[key] || null;
      } catch (error) {
        console.error('获取本地数据失败:', error);
        return null;
      }
    },
  }
}
</script>

<style scoped>
.logistics-monitor-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-button {
  margin: 0;
}

.el-table {
  margin-top: 15px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style> 